<?php

namespace service;

// 1.获取数据，插入数据。
// 2.数据来源file or string or 生成
// 2.1 file 使用上传的，string 用 \n分割，生成的直接是数组？预览的话？？？？存js先？就变成和前一个一样的了。
// 生成sql数据，插入，返回结果。

/**
 * 文件?string?
 */
class File2Array
{

    protected $file_path, $file;
    protected $max_line_length = 2000;

    /**
     * init
     * @param string $path
     */
    public function __construct($path = null)
    {
        if (file_exists($path)) {
            $this->file = fopen($this->file_path = $path, 'rb');
        } else {
            die('invalid file path');
        }
    }

    /**
     * toArray
     *
     * @param  string $file file path
     * @param  string $delimiter string delimiter
     * @return array
     */
    public function toArray($file = '', $delimiter = "\t")
    {
        $file and $this->setFile($file);
        if (!$this->file) {
            return [];
        }
        $handle = $this->file;
        $result = [];
        while (($data = fgetcsv($handle, $this->max_line_length, $delimiter)) !== false) {
            $result[] = $data;
        }
        return $result;
    }

    /**
     * setFile
     * @param string $path
     * @return resource|false
     */
    public function setFile($path = '')
    {
        if (file_exists($path)) {
            fclose($this->file);
            return $this->file = fopen($this->file_path = $path, 'rb');
        }
        return false;
    }

    /**
     * getDelimiter
     *
     * @param  string $str
     * @return string|null
     */
    protected function getDelimiter($str = null)
    {
        if (is_string($str) && $str) {
            $str = strstr($str, "\n", true) ?: $str;
            $t = "\t";
            $s = ',';
            return substr_count($str, $t) > substr_count($str, $s) ? $t : $s;
        }
    }
}

class mdSerialNo
{
    protected static $lists = [];
    public static $table = 'md_table';

    /**
     * toArray 直接preg_split/split也行
     *
     * @param  string $str
     * @param  string $delimiter
     * @return array
     */
    public static function strToArray($str = '', $delimiter = "\n")
    {
        if ($str && $delimiter && is_string($str) && is_string($delimiter)) {
            return explode($delimiter, $str);
        }
        return [];
    }

    /**
     * csvToArray
     *
     * @param  string $str
     * @param  string $delimiter
     * @return array
     */
    public static function csvToArray($str = '', $delimiter = ',')
    {
        $result = [];
        if (is_string($str)) {
            $str = [$str];
        }
        foreach ($str as $key => $val) {
            $result[] = str_getcsv($val, $delimiter);
        }
        return $result;
    }

    /**
     * create md serial number
     *
     * @param  integer  $start start
     * @param  integer  $end
     * @param  integer $step
     * @return array
     */
    public static function createMdNo($start = null, $end = null, $step = 1)
    {
        if ($start === null) {
            return [];
        } elseif ($end === null) {
            $end = $start + 100;
        }
        static $_lists = [];
        $_key = md5($start . $end . $step);
        return isset($_lists[$_key]) ? $_lists[$_key] : $_lists[$_key] = range($start, $end, $step);
    }

    /**
     * arrayToSql
     *
     * @param  array  $data
     * @return string
     */
    public static function arrayToSql(array $data = [], $replace = false)
    {
        if (is_array($data)) {
            //统一当作多数组处理
            if (!is_array(current($data))) {
                $data = [$data];
            }
            $fields = array_keys(current($data));
            $sql = ($replace ? 'REPLACE' : 'INSERT') . ' INTO `' . static::$table . '` (`' . implode('`, `', $fields) . '` ) VALUES ';
            $values = '';
            foreach ($data as $key => $value) {
                $values .= '("' . implode('", "', $value) . '"),';
            }
            return $sql . trim($values, ',');
        }
    }

    /**
     * buildInsertData
     *
     * @param  array  $data
     * @param  array  $common_data
     * @return array
     */
    public static function buildInsertData(array $data = [], array $common_data = [])
    {
        if (!static::verifyCommonData($common_data)) {
            return false;
        }
        $insert_data = [];
        foreach ($data as $k => $val) {
            $insert_data[] = ['md_no' => $val] + $common_data;
        }
        return $insert_data;
    }

    /**
     * verifyCommonData
     *
     * @param  array  $data
     * @return boolean
     */
    protected static function verifyCommonData(array $data)
    {
        $common_data = [];
        return count(array_intersect_key($data, $common_data)) === count($common_data);
    }

    /**
     * getCsvStringDelimiter
     *
     * @param  string $str
     * @return string|null
     */
    protected static function getCsvStringDelimiter($str = null)
    {
        if (is_string($str) && $str) {
            $str = strstr($str, "\n", true) ?: $str;
            $t = "\t";
            $s = ',';
            return substr_count($str, $t) > substr_count($str, $s) ? $t : $s;
        }
    }
}
